package com.qf.controller;

import java.io.BufferedReader;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * LoginController负责打开登录页面(GET请求)和登录出错页面(POST请求)，
 * 
 * 真正登录的POST请求由Filter完成,
 * 
 */
@Controller
public class LoginController {

	@RequestMapping(value = "/test", method = { RequestMethod.GET,
			RequestMethod.POST })
	// @ResponseBody
	public String test(HttpServletRequest request) {
		String urlParam = request.getParameter("t");
		String jsonBody = getJsonBody(request);
		System.out.println("urlParam:" + urlParam + ",jsonBody:" + jsonBody);
		return "forward:/test1";
	}

	@RequestMapping(value = "/test1", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
	private String test1(HttpServletRequest request) {
		String urlParam = request.getParameter("t");
		String jsonBody = getJsonBody(request);
		System.out.println("urlParam:" + urlParam + ",jsonBody:" + jsonBody);
		return "urlParam:" + urlParam + ",jsonBody:" + jsonBody;
	}

	@RequestMapping(value = "/login", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
	private String getJsonBody(HttpServletRequest request) {
		return readJsonFromRequestBody(request);
	}

	/**
	 * 请求校验username是否等于admin
	 */
	@RequestMapping(value = "checkUsername")
	@ResponseBody
	public boolean checkLoginName(@RequestParam("username") String username) {
		return "admin".equalsIgnoreCase(username);
	}

	private String readJsonFromRequestBody(HttpServletRequest request) {
		// TODO Auto-generated method stub
		String jsonData = "";
		try {
			BufferedReader reader = request.getReader();
			StringBuffer buffer = new StringBuffer("");
			String temp;
			while ((temp = reader.readLine()) != null) {
				buffer.append(temp);
			}
			reader.close();
			jsonData = buffer.toString();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonData;
	}

}
